package com.hqyj.springBoot.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter(filterName = "parameterFilter",urlPatterns = "/*")
public class ParameterFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ParameterFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        LOGGER.debug("============ ParameterFilter DoFilter ============ ");



        
        // 1、转换为HttpServletRequest、HttpServletResponse对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 2、request获取所有的查询参数
        //request.getParameterMap()  ----返回的map是可读不可写
        //request对象,不允许增删改
        //使用HttpServletRequestWrapper对象操作
        //重写Wrapper实现接口中的getParameter方法,然后将wrapper对象交出去

        //重写方式：1、创建一个类继承wrapper，重写方法 2、直接在直接在new的时候进行重写
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request){
            @Override
            public String getParameter(String name) {
                //重写方法，替换fuck字符串

                String value = super.getParameter(name);
                if (value.contains("fuck")){
                    return value.replaceAll("fuck","****");
                }else {
                    return value;
                }
            }

            @Override
            public String[] getParameterValues(String name) {
                //将所有同name值取出来,遍历所有值
                String[] values = super.getParameterValues(name);
                return Arrays.asList(values).stream()
                        .map(item -> item.replaceAll("fuck","****"))
                        .toArray(String[] :: new);
            }
        };
        filterChain.doFilter(wrapper,response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("============ ParameterFilter Init ============ ");
    }

    @Override
    public void destroy() {
        LOGGER.debug("============ ParameterFilter Destroy ============ ");
    }
}
